import asyncio
from typing import Dict, Any, List, Optional
from datetime import datetime, date, timedelta
from enum import Enum
import json
import uuid
from collections import defaultdict

from ..models.audit_models import AuditResult, AuditLog, AuditDecision
from ..utils.logger import get_logger

logger = get_logger(__name__)


class AuditLogger:
    """审核日志记录器."""
    
    def __init__(self):
        # 简化版本 - 使用内存存储，生产环境应使用数据库
        self.audit_logs: List[AuditLog] = []
        self.audit_results: List[AuditResult] = []
        
    async def log_audit_action(self, action: str, request_id: str, 
                              executor_type: str = "system",
                              executor_id: Optional[str] = None,
                              action_details: Optional[Dict[str, Any]] = None,
                              success: bool = True,
                              error_message: Optional[str] = None) -> str:
        """记录审核操作."""
        
        log_entry = AuditLog(
            request_id=request_id,
            action=action,
            action_details=action_details,
            executor_type=executor_type,
            executor_id=executor_id,
            success=success,
            error_message=error_message
        )
        
        self.audit_logs.append(log_entry)
        logger.info(f"记录审核操作: {action} for {request_id}")
        
        return log_entry.log_id
    
    async def save_audit_result(self, result: AuditResult) -> str:
        """保存审核结果."""
        self.audit_results.append(result)
        
        # 同时记录操作日志
        await self.log_audit_action(
            action="audit_completed",
            request_id=result.request_id,
            action_details={
                "decision": result.decision.value,
                "score": result.final_score,
                "confidence": result.confidence_level
            }
        )
        
        logger.info(f"保存审核结果: {result.request_id}, 决策: {result.decision}")
        return result.result_id
    
    def get_audit_history(self, 
                         page: int = 1,
                         page_size: int = 10,
                         status: Optional[str] = None,
                         classroom_id: Optional[str] = None,
                         date_from: Optional[date] = None,
                         date_to: Optional[date] = None) -> Dict[str, Any]:
        """获取审核历史记录."""
        
        # 过滤结果
        filtered_results = self.audit_results.copy()
        
        if status:
            filtered_results = [r for r in filtered_results if r.decision.value == status]
        
        if classroom_id:
            # 需要从请求数据中获取classroom_id，这里简化处理
            pass
        
        if date_from or date_to:
            # 根据创建时间过滤
            for result in filtered_results.copy():
                result_date = result.created_at.date()
                if date_from and result_date < date_from:
                    filtered_results.remove(result)
                    continue
                if date_to and result_date > date_to:
                    filtered_results.remove(result)
                    continue
        
        # 排序和分页
        filtered_results.sort(key=lambda x: x.created_at, reverse=True)
        
        start_idx = (page - 1) * page_size
        end_idx = start_idx + page_size
        page_results = filtered_results[start_idx:end_idx]
        
        return {
            "total_count": len(filtered_results),
            "page": page,
            "page_size": page_size,
            "results": page_results
        }
    
    def get_audit_statistics(self, 
                           date_from: Optional[date] = None,
                           date_to: Optional[date] = None) -> Dict[str, Any]:
        """获取审核统计信息."""
        
        # 过滤时间范围
        results = self.audit_results.copy()
        if date_from or date_to:
            filtered_results = []
            for result in results:
                result_date = result.created_at.date()
                if date_from and result_date < date_from:
                    continue
                if date_to and result_date > date_to:
                    continue
                filtered_results.append(result)
            results = filtered_results
        
        if not results:
            return {
                "total_requests": 0,
                "approved_count": 0,
                "rejected_count": 0,
                "pending_count": 0,
                "average_processing_time_ms": 0,
                "approval_rate": 0
            }
        
        # 统计各种决策
        decision_counts = defaultdict(int)
        total_processing_time = 0
        
        for result in results:
            decision_counts[result.decision.value] += 1
            total_processing_time += result.processing_time_ms
        
        total_requests = len(results)
        approved_count = decision_counts.get("approved", 0)
        rejected_count = decision_counts.get("rejected", 0)
        pending_count = decision_counts.get("pending", 0)
        
        approval_rate = approved_count / total_requests if total_requests > 0 else 0
        avg_processing_time = total_processing_time / total_requests if total_requests > 0 else 0
        
        return {
            "total_requests": total_requests,
            "approved_count": approved_count,
            "rejected_count": rejected_count,
            "pending_count": pending_count,
            "average_processing_time_ms": avg_processing_time,
            "approval_rate": approval_rate
        }
    
    def get_audit_logs(self, request_id: Optional[str] = None,
                      limit: int = 100) -> List[AuditLog]:
        """获取审核日志."""
        logs = self.audit_logs.copy()
        
        if request_id:
            logs = [log for log in logs if log.request_id == request_id]
        
        # 按时间排序并限制数量
        logs.sort(key=lambda x: x.timestamp, reverse=True)
        return logs[:limit]
    
    def generate_report(self, report_type: str = "daily",
                       target_date: Optional[date] = None) -> Dict[str, Any]:
        """生成审核报表."""
        
        if not target_date:
            target_date = date.today()
        
        if report_type == "daily":
            date_from = target_date
            date_to = target_date
        elif report_type == "weekly":
            date_from = target_date - timedelta(days=target_date.weekday())
            date_to = date_from + timedelta(days=6)
        elif report_type == "monthly":
            date_from = target_date.replace(day=1)
            if target_date.month == 12:
                date_to = date_from.replace(year=target_date.year + 1, month=1) - timedelta(days=1)
            else:
                date_to = date_from.replace(month=target_date.month + 1) - timedelta(days=1)
        else:
            raise ValueError(f"不支持的报表类型: {report_type}")
        
        # 获取统计数据
        stats = self.get_audit_statistics(date_from, date_to)
        
        # 按日期分组的详细统计
        daily_stats = defaultdict(lambda: defaultdict(int))
        
        for result in self.audit_results:
            result_date = result.created_at.date()
            if date_from <= result_date <= date_to:
                date_str = result_date.isoformat()
                daily_stats[date_str]["total"] += 1
                daily_stats[date_str][result.decision.value] += 1
        
        return {
            "report_type": report_type,
            "period": {
                "from": date_from.isoformat(),
                "to": date_to.isoformat()
            },
            "summary": stats,
            "daily_breakdown": dict(daily_stats),
            "generated_at": datetime.now().isoformat()
        }


# 全局审核日志记录器实例
_audit_logger = None

def get_audit_logger() -> AuditLogger:
    """获取审核日志记录器单例."""
    global _audit_logger
    if _audit_logger is None:
        _audit_logger = AuditLogger()
    return _audit_logger